package com.abo.yaas.webservice;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;

import com.abo.yaas.domain.User;
import com.abo.yaas.webservice.constants.URLConstants;
import com.abo.yaas.webservice.exceptions.WebServiceException;
import com.abo.yaas.webservice.utils.AuthenticationUtil;
import com.abo.yaas.webservice.utils.PasswordUtil;
import com.abo.yaas.webservice.utils.UserFacade;
import com.sun.jersey.spi.resource.Singleton;

@Singleton
@Path(URLConstants.userProvider)
public class UserResource extends EntityResource<User> {
    public UserResource() {
        super(User.class);
    }

    @GET
    @Path(URLConstants.authentication)
    @Produces(MediaType.APPLICATION_XML)
    public User authenticate(@Context HttpHeaders headers) throws WebServiceException {
        return AuthenticationUtil.authenticate(getUser(headers), getPassword(headers));
    }

    @POST
    @Path(URLConstants.register)
    @Consumes(MediaType.APPLICATION_XML)
    @Produces(MediaType.APPLICATION_XML)
    public User register(User user, @Context HttpHeaders headers) throws WebServiceException {
        return UserFacade.register(user);
    }

    @Override
    @POST
    @Produces(MediaType.APPLICATION_XML)
    public User saveOrUpdateEntity(User entity, @Context HttpHeaders headers) {
        if (!entity.getDuplicatePassword().isEmpty()) {
            UserFacade.changePassword(entity);
        }
        entity.setPasswordHash(PasswordUtil.generateHashedPassword(entity.getPassword()));
        return super.saveOrUpdateEntity(entity, headers);
    }
}
